package com.jmpt.fangbohui.http;

import java.net.URI;

import org.apache.http.Header;
import org.apache.http.client.CookieStore;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.protocol.HttpContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import cn.jpush.android.api.e;

import com.jmpt.fangbohui.Constants;
import com.jmpt.fangbohui.MyApplication;
import com.jmpt.fangbohui.R;
import com.jmpt.fangbohui.utils.DebugLog;
import com.jmpt.fangbohui.utils.ToastHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
/**
 * json 数据处理器 基类  ，并且实现在开始(onStart)访问网络时获取本地缓存
 * @author Victor
 *
 */
public class JsonHttpHandler extends AsyncHttpResponseHandler {
    private Context mContext;
    private ProgressDialog mProgressDialog;
    private boolean isShowProgressDialog = false;
    private boolean isShowErrorMessage = true;
    private boolean isProgressDialogCancleable = false;
    private String mDialogMessage;
    
    /**
	 * 是否需要获取缓存  默认不获取缓存
	 */
	private boolean fromCache = false;

	public JsonHttpHandler(Context context) {
		this.mContext = context;
	}
	
    public JsonHttpHandler(Context context,boolean fromCache) {
        this.mContext = context;
        this.fromCache = fromCache;
    }
    
    
    /**
     * 请求成功 (statusCode = 200) 获取到来自服务器的信息
     */
    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
    	
    	DebugLog.i("responseBody length : " + responseBody.length);
    	
        String responseString = null;
        try {
            responseString = new String(responseBody, "UTF-8").trim();
            responseString = responseString.substring(responseString.indexOf("{"), 
            		responseString.lastIndexOf("}") + 1);
            responseString.indexOf("{");
            JSONObject response = null;
            DebugLog.i("statusCode:" + statusCode);
            DebugLog.i("responseString:" + responseString);
            
            response = new JSONObject(responseString);
            boolean done = response.getBoolean("done");
            String msg = response.getString("msg");

            if (done) {
                try {
                    JSONObject retval = response.getJSONObject("retval");
                    
                    //走到这里 说明 retval 是一段可以封装成普通对象json数据 (以"{"开头  "}"结尾 )
                    //将这个json对象传给接收的页面
                    onDo(retval);
                } catch (JSONException e) {
                	//走到这里 说明 retval 不是一段合法的json数据  
                	//可能是一段字符串  也  可能是 一个数组数据 (以"["开头  "]"结尾 )
                    try {
                        JSONArray data = response.getJSONArray("retval");
                        //是 一个数组数据 (以"["开头  "]"结尾 )
                        onDo(data);
                    } catch (Exception e2) {
                    }
                }finally{
                	//可能一个普通的字符串数据
                	String retval = response.getString("retval");
                    onDo(retval);
                    //保存到本地缓存
                    saveToCache(retval);
                }
            } else {
                onFail(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            onFail("数据出错");
        }

    }
    /**
     * 保存到本地
     * @param retval
     */
    private void saveToCache(String retval) {	
		MyApplication.getSharedPreferences().edit()
				.putString(getRequestURI().toString(), retval)
				.commit();
	}	

	/**
     * 请求失败 statusCode 200 以外
     */
    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
        if (mContext != null) {
            try {
                if (statusCode == 0) {
                    ToastHelper.ShowToast(R.string.error_http_fail_connet_server, mContext);
                    onFail(mContext.getString(R.string.error_http_fail_connet_server));
                } else if (statusCode >= 400) {
                    ToastHelper.ShowToast(R.string.error_http_request, mContext);
                    onFail(mContext.getString(R.string.error_http_request));
                } else if (statusCode >= 500) {
                    ToastHelper.ShowToast(R.string.error_http_server_error, mContext);
                    onFail(mContext.getString(R.string.error_http_server_error));
                } else {
                    ToastHelper.ShowToast(R.string.error_http_server_busy, mContext);
                    onFail(mContext.getString(R.string.error_http_server_busy));
                }
            } catch (Exception exception) {
                exception.printStackTrace();
                onFail("");
            }
        }
    }
    /**
     * 接收普通对象
     * @param response
     */
    public void onDo(JSONObject response) {
    	
    }
    /**
     * 接收数组对象
     * @param response
     */
    public void onDo(JSONArray response) {
    	
    }
    /**
     * 字符串数据
     * @param response
     */
    public void onDo(String response) {
    	System.out.println(response);
    }
    
    /**
     * 接收普通对象
     * @param response
     */
    public void onCacheDo(JSONObject cache) {

    }
    /**
     * 接收数组对象
     * @param response
     */
    public void onCacheDo(JSONArray cache) {

    }
    /**
     * 字符串数据
     * @param response
     */
    public void onCacheDo(String cache) {
    	
    }
    /**
     * 错误回调函数
     * @param msg 错误信息
     */
    public void onFail(String msg) {
        if (TextUtils.isEmpty(msg) == false && mContext != null) {
            if (isShowErrorMessage == true) {
                ToastHelper.ShowToast(msg, mContext);
            }
        }
    }


    @Override
    public void onStart() {
        super.onStart();
        DebugLog.i("uri : " + getRequestURI().getPath());
        if (isShowProgressDialog) {
            mProgressDialog = new ProgressDialog(mContext);
            if (TextUtils.isEmpty(mDialogMessage)) {
                mProgressDialog.setMessage(mContext.getString(R.string.message_loading));
            } else {
                mProgressDialog.setMessage(mDialogMessage);
            }
            mProgressDialog.setCanceledOnTouchOutside(false);
            mProgressDialog.setCancelable(isProgressDialogCancleable);
            mProgressDialog.show();
        }
        //获取本地缓存
        if(fromCache){
        	findCache();
        }
        
        HttpContext httpContext = AsyncHttp.getClient().getHttpContext();
        CookieStore cookies = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);
        if (cookies != null) {
            for (Cookie c : cookies.getCookies()) {
                DebugLog.i("cookies " + c.getName() + ":" + c.getValue());
            }
        } else {
            DebugLog.i("cookies " + "cookies is null");
        }
    }

    private void findCache() {
    	//拿到当前访问的uri
		URI uri = getRequestURI();
		//跟据uri去本地缓存早
		String json = MyApplication.getSharedPreferences().getString(uri.toString(), "");
		if(!TextUtils.isEmpty(json)){
			DebugLog.d("onCacheSuccess -- (" + getRequestURI() + ") : " + json);
			onCacheSuccess(json);
		}else{
			onCacheFail();
			DebugLog.d("onCacheSuccess -- (" + getRequestURI() + ")");
		}
	}
    /**
     * 没有本地缓存
     */
	public void onCacheFail() {
		// 没有缓存
	}

	/**
	 * 成功获取本地缓存
	 * @param json
	 */
	public void onCacheSuccess(String json) {
		try {
            JSONObject retval = new JSONObject(json);
            //走到这里 说明 retval 是一段可以封装成普通对象json数据 (以"{"开头  "}"结尾 )
            //将这个json对象传给接收的页面
            onCacheDo(retval);
        } catch (JSONException e) {
        	//走到这里 说明 retval 不是一段合法的json数据  
        	//可能是一段字符串  也  可能是 一个数组数据 (以"["开头  "]"结尾 )
            try {
                JSONArray data = new JSONArray(json);
                
                //是 一个数组数据 (以"["开头  "]"结尾 )
                onCacheDo(data);
                
            } catch (Exception e2) {
            	e2.printStackTrace();
            }
        }finally{
        	//可能一个普通的字符串数据
        	onCacheDo(json);
        }
	}

	@Override
    public void onFinish() {
        super.onFinish();
        if (isShowProgressDialog && mProgressDialog != null && mProgressDialog.isShowing()) {
            try {
                mProgressDialog.dismiss();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public JsonHttpHandler setShowProgressDialog(String message) {
        isShowProgressDialog = true;
        this.mDialogMessage = message;
        return this;
    }

    public void setProgressDialogCancleable(boolean cancleable) {
        isProgressDialogCancleable = cancleable;
    }

    public void showProgressDialog() {
        isShowProgressDialog = true;
    }

    public void hideErrorMessage() {
        isShowErrorMessage = false;
    }

}
